// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});

var trendsList, now;
function createXMLHttpRequest(){   
    var xmlHttp = null; 
    if(window.ActiveXObject){    
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");    
    }else if(window.XMLHttpRequest){    
        xmlHttp = new XMLHttpRequest();    
    }
    return xmlHttp;
}

function setCurrent(){
	var myDate = new Date();
	var year = myDate.getFullYear();
	var month = myDate.getMonth() + 1; //1~12
	var day = myDate.getDate();
	var hour = myDate.getHours()-1;
	document.getElementById("month").value = month;
	document.getElementById("year").value = year;
	document.getElementById("day").value = day;
	document.getElementById("hour").value = hour;
}

//show 10 trends offered by Twitter
function show10(){
	var list = document.getElementById("trendlist");
	var lis = list.childNodes;
	for(var i=0; i<10; i++){
		lis[i].innerHTML = "<a href=\"#\">"+trendsList[now]+"</a>";
		now++;
		if(now == trendsList.length){
			now = 0;
		}
	}
}

//Lock or unlock a trend
function lockOrUnlock(){
	var lockedTrend = document.getElementById("lockedTrend");
	var locker = document.getElementById("locker");
	var trend = document.getElementById("curTrend").innerHTML;
	if(lockedTrend.value == ""){
		lockedTrend.value = trend;
		locker.innerHTML = "[unlock]";
	}else{
		lockedTrend.value = "";
		locker.innerHTML = "[lock]";
	}
}

//called when the time is changed
function ontimechange(){
	var hour = $("#SliderSingle").slider("calculatedValue");
	document.getElementById("hour").value = hour;
	var year = document.getElementById("year").value;
	var month = document.getElementById("month").value; //1~12
	var day = document.getElementById("day").value;
	var myDate = new Date();
	var curYear = myDate.getFullYear();
	var curMonth = myDate.getMonth() + 1; //1~12
	var curDay = myDate.getDate();
	var curHour = myDate.getHours()-1;
	if(year>curYear || month>curMonth || day>curDay || (year==curYear && month==curMonth && day==curDay && hour>curHour)){
		alert("You can't see the future!");
	}else{
		var lockedTrend = document.getElementById("lockedTrend");
		if(lockedTrend.value != ""){
			getKeywords();
			getNews();
			getFlickr();
			getYoutube();
			showChart();
		}else{
			getAllTrends();
		}
	}

}

//get trends according to the given date and time, and save them in the trendsList
function getAllTrends(){
	var year = document.getElementById("year").value;
	var month = document.getElementById("month").value; //1~12
	var day = document.getElementById("day").value;
	var hour = document.getElementById("hour").value;
	getTrendsByYMDH(year, month, day, hour);
	now = 0;
	show10();
}

//get trends according to the given year, month, day, and hour
function getTrendsByYMDH(y, m, d, h){
	var xmlHttp = createXMLHttpRequest();        
	xmlHttp.onreadystatechange= function  (){    
		if(xmlHttp.readyState == 4 && xmlHttp.status == 200){    
			var str = xmlHttp.responseText;
			trendsList = JSON.parse(str);
		}
	};    
	var url="trends/getAllTrends?year="+y+"&month="+m+"&day="+d+"&hour="+h;
	xmlHttp.open("GET",url,false);    
	xmlHttp.send();  
}

function getResults(){
	var lockedTrend = document.getElementById("lockedTrend");
	if(lockedTrend.value != ""){
		alert("Current Trend is locked! To change it you should unlock it first."+lockedTrend.value);
	}else{
		var trend = this.childNodes[0].innerHTML;
		document.getElementById("curTrend").innerHTML = trend;
		setTab(0);
		getKeywords();
		getNews();
		getFlickr();
		getYoutube();
		showChart();
	}
}

function getKeywords(){
	var lockedTrend = document.getElementById("lockedTrend");
	var curTrend = document.getElementById("curTrend").innerHTML;
	var trend;
	if(lockedTrend.value == ""){
		trend = curTrend;
	}else{
		trend = lockedTrend.value;
	}
	var year = document.getElementById("year").value;
	var month = document.getElementById("month").value; //1~12
	var day = document.getElementById("day").value;

	var xmlHttp = createXMLHttpRequest();       
	xmlHttp.onreadystatechange= function (){    
		if(xmlHttp.readyState == 4 && xmlHttp.status == 200){    
			var str = xmlHttp.responseText;
			var arr = JSON.parse(str);
			var keywords = document.getElementById("keywords");
			keywords.innerHTML = "";
			for(var i=0; i<arr.length; i++){
				keywords.innerHTML += (" "+arr[i]);
			}
		}
	}; 
	var url="trends/getKeywords?year="+year+"&month="+month+"&day="+day+"&trend="+trend;    
	xmlHttp.open("GET",url,false);    
	xmlHttp.send();
}
function getNews(){
	var lockedTrend = document.getElementById("lockedTrend");
	var curTrend = document.getElementById("curTrend").innerHTML;
	var trend;
	if(lockedTrend.value == ""){
		trend = curTrend;
	}else{
		trend = lockedTrend.value;
	}
	var year = document.getElementById("year").value;
	var month = document.getElementById("month").value; //1~12
	var day = document.getElementById("day").value;

	//get Yahoo! news
	var xmlHttp = createXMLHttpRequest();   
	xmlHttp.onreadystatechange= function  (){    
		if(xmlHttp.readyState == 4 && xmlHttp.status == 200){    
			var str = xmlHttp.responseText;
			var arr = JSON.parse(str);
			var news = document.getElementById("news_div");
			news.innerHTML = "";
			for(var i=0; i<arr.length; i++){
				news.innerHTML += "<div class = \"news\"><a href =' "+arr[i].url+"' target = \"view_window\">link</a><p>"+arr[i].content+"</p></div>";
			}
		}
	};    
	var url="trends/getNews?year="+year+"&month="+month+"&day="+day+"&trend="+trend;  
	xmlHttp.open("GET",url,false);    
	xmlHttp.send();  
}
function getFlickr(){
	var lockedTrend = document.getElementById("lockedTrend");
	var curTrend = document.getElementById("curTrend").innerHTML;
	var trend;
	if(lockedTrend.value == ""){
		trend = curTrend;
	}else{
		trend = lockedTrend.value;
	}
	var year = document.getElementById("year").value;
	var month = document.getElementById("month").value; //1~12
	var day = document.getElementById("day").value;
	var hour = document.getElementById("hour").value;
	
	var xmlHttp = createXMLHttpRequest();   
	xmlHttp.onreadystatechange= function  (){    
		if(xmlHttp.readyState == 4 && xmlHttp.status == 200){    
			var str = xmlHttp.responseText;
			var result = JSON.parse(str);
			//var flickrDiv = document.getElementById("flickr_div");
			//flickrDiv.innerHTML = "";
			var left = document.getElementById("leftPhoto");
			var right = document.getElementById("rightPhoto");
			left.innerHTML = "";
			right.innerHTML = "";
			var temp;
			for(var i = 0;i<result.length&&i<10; i++){
				temp = result[i];
				if(i%2 == 0){
					left.innerHTML+= "<image src=\"http://farm"+temp.farm+".staticflickr.com/"+temp.server+"/"+temp.id+"_"+temp.secret+".jpg\"/>";
				}else{
					right.innerHTML+= "<image src=\"http://farm"+temp.farm+".staticflickr.com/"+temp.server+"/"+temp.id+"_"+temp.secret+".jpg\"/>";
				}
			}	
		}
	};
	var url="trends/getPhotoInfo?year="+year+"&month="+month+"&day="+day+"&hour="+hour+"&trend="+trend;
	xmlHttp.open("POST",url,false);    
	xmlHttp.send();
}

function getYoutube(){
	var lockedTrend = document.getElementById("lockedTrend");
	var curTrend = document.getElementById("curTrend").innerHTML;
	var trend;
	if(lockedTrend.value == ""){
		trend = curTrend;
	}else{
		trend = lockedTrend.value;
	}
	var year = document.getElementById("year").value;
	var month = document.getElementById("month").value; //1~12
	var day = document.getElementById("day").value;
	
	//get search keywords
	var searchKeywords = new Array();
	var xmlHttp = createXMLHttpRequest();   
	xmlHttp.onreadystatechange= function  (){    
		if(xmlHttp.readyState == 4 && xmlHttp.status == 200){    
			var str = xmlHttp.responseText;
			searchKeywords = JSON.parse(str);
		}
	}; 
	var url="trends/getSearchKeywords?year="+year+"&month="+month+"&day="+day+"&trend="+trend;  
	xmlHttp.open("GET",url,false);    
	xmlHttp.send();
	
	//get youtube
	var xmlHttp = createXMLHttpRequest();   
	xmlHttp.onreadystatechange= function  (){
		if(xmlHttp.readyState == 4 && xmlHttp.status == 200){    
			var str = xmlHttp.responseText;
			var result = JSON.parse(str);
			var youtubeDiv = document.getElementById("youtube_div");
			youtubeDiv.innerHTML = "";
			var videos = result.feed.entry;
			for(var i=0; i<videos.length && i<5; i++){
				var temp = videos[i];
				var video_id = temp.media$group.yt$videoid.$t;
				youtubeDiv.innerHTML += "<div id = \"video"+i+"\">hahahahah</div>";
				new YT.Player("video"+i, {
					width: '640',
					height: '390',
					videoId: video_id
					}
				);
			}
		}
	};
	var url="https://gdata.youtube.com/feeds/api/videos?max-results=5&v=2&alt=json&q=";
	for(var i=0; i<searchKeywords.length; i++){
		if(i == 0){
			url += searchKeywords[i];
		}else{
			url+= (" "+searchKeywords[i]);
		}
	}
	xmlHttp.open("GET",url,false);    
	xmlHttp.send();  
	
}

function showChart(){
	showEmotionChart();
	showDevChart();
}
function showEmotionChart(){
	var lockedTrend = document.getElementById("lockedTrend");
	var curTrend = document.getElementById("curTrend").innerHTML;
	var trend;
	if(lockedTrend.value == ""){
		trend = curTrend;
	}else{
		trend = lockedTrend.value;
	}
	var year = document.getElementById("year").value;
	var month = document.getElementById("month").value; //1~12
	var day = document.getElementById("day").value;
	var hour = document.getElementById("hour").value;
	
	var xmlHttp = createXMLHttpRequest();     
	xmlHttp.onreadystatechange= function  (){    
		if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
			var str = xmlHttp.responseText;
			var arr = JSON.parse(str);
			//alert(arr[0]+"-"+arr[1]+"-"+arr[2]+"-"+arr[3]);
		    	  // Create the data table.
		    	var data = new google.visualization.DataTable();
		    	  data.addColumn('string', 'Topping');
		    	  data.addColumn('number', 'Slices');
		    	  data.addRows([
		    	    ['Positive', arr[0]],
		    	    ['Negative', arr[1]],
		    	    ['Neutral', arr[2]],
		    	    ['Irrelative', arr[3]]
		    	  ]);

		    	  // Set chart options
		    	  var options = {'title':'People\'s Attitude',
		    	                 'width':400,
		    	                 'height':300};

		    	  // Instantiate and draw our chart, passing in some options.
		    	  var chart = new google.visualization.PieChart(document.getElementById('emotionChart'));
		    	  chart.draw(data, options);
		}
		
	};
	var url="trends/getEmotions?year="+year+"&month="+month+"&day="+day+"&hour="+hour+"&trend="+trend;    
	xmlHttp.open("GET",url,false);
	xmlHttp.send(); 
}

function showDevChart(){
	var lockedTrend = document.getElementById("lockedTrend");
	var curTrend = document.getElementById("curTrend").innerHTML;
	var trend;
	if(lockedTrend.value == ""){
		trend = curTrend;
	}else{
		trend = lockedTrend.value;
	}
	var year = document.getElementById("year").value;
	var month = document.getElementById("month").value; //1~12
	var day = document.getElementById("day").value;
	var hour = document.getElementById("hour").value;
	
	var xmlHttp = createXMLHttpRequest();
	xmlHttp.onreadystatechange= function  (){
		if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
			var str = xmlHttp.responseText;
			var arr = JSON.parse(str);
			//alert(arr[0]+"-"+arr[1]+"-"+arr[2]+"-"+arr[3]);
			// Create the data table.
			var data = google.visualization.arrayToDataTable([
			                                                    ['Day', 'Hottness'],
			                                                    ['-6',  arr[0]],
			                                                    ['-5',  arr[1]],
			                                                    ['-4',  arr[2]],
			                                                    ['-3',  arr[3]],
			                                                    ['-2',  arr[4]],
			                                                    ['yestoday',  arr[5]],
			                                                    ['today',  arr[6]]
			                                                  ]);

			var options = {title: 'Development in recent 7 days'};

			var chart = new google.visualization.LineChart(document.getElementById('devChart'));
			chart.draw(data, options);
		}
	};
	var url="trends/getRecentTrendFrequency?year="+year+"&month="+month+"&day="+day+"&hour="+hour+"&trend="+trend;    
	xmlHttp.open("GET",url,false);
	xmlHttp.send(); 
	
}

//add listener for some tags
function addListener(){
	var lis = document.getElementById("trendlist");
	for(var i=0; i<lis.childNodes.length; i++){
		lis.childNodes[i].addEventListener("click", getResults, false);
	}
	
}

var tabList = new Array();
tabList.push("news");
tabList.push("flickr");
tabList.push("youtube");
tabList.push("chart");
function setTab(i){
	var menu;
	var content;
	var j;
	for(j=0; j<tabList.length; j++){
		menu = tabList[j]+"_menu";
		content = tabList[j]+"_div";
		if(j != i){
			document.getElementById(menu).className = "";
			document.getElementById(content).style.display = "none";
		}else{
			document.getElementById(content).style.display = "block";
			document.getElementById(menu).className = "selected";
		}
	}
	
}


function init(){
	addListener();
	
	//set the Date and Time to be current
	setCurrent();
	
	//get twitter trends according the Date and Time
	getAllTrends();
	
}
